// pages/Gauthor/Gauthor.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    historyShow: false,
    options: [], //组别
    roleShow: null, //权限权重，实现某些项目显示隐藏
    showindex: true, //是否显示市场部
    //市场经理  index = 9
    identity: '',
    offset:0,
    cheks: [{
        name: '',
        code: 'renter_ceo',
        chek: 0
      }, //总经理 4
      {
        name: '',
        code: 'renter_marketing_manager',
        chek: 0
      }, //市场经理 9
      {
        name: '',
        code: 'renter_finance_manager',
        chek: 0
      }, //财务经理 8
      {
        name: '',
        code: 'renter_logistics_manager',
        chek: 0
      }, //后勤经理 10
      {
        name: '',
        code: 'renter_marketing_staff',
        chek: 0
      }, //市场专员 14
      {
        name: '',
        code: 'renter_outsourcing_manager',
        chek: 0
      }, //合伙人管理 11
      {
        name: '',
        code: 'renter_outsourcing_staff',
        chek: 0
      }, //合伙专员 12
    ],
    actived_role: {
      name: 'null',
      chek: 0
    }, //认证用户规则
    value: '',
    // status:'',
    checked: true,
    roleIndex: "",
    delGroupId: '', //删除数组id
    userData: {}, //被点击用户数据
    userMedata: '',
    remind: [ //浏览记录
      {
        id: 1,
        orderid: "3248956565f5656",
        fangyuanTag: 1,
        favprice: 75,
        oriprice: 180,
        address: '广州市番禺区石岗路地址地址地址地址地址',
        time: '2020/09/06-2020/09/28',
        tabs: ["4.1折", "491.23㎡", "变卖"]
      },
      {
        id: 2,
        orderid: "32fafa489565655656",
        fangyuanTag: 2,
        favprice: 105,
        oriprice: 280,
        address: '广州市番禺区石岗路地址地址地址',
        time: '2020/09/09-2020/09/24',
        tabs: ["2.7折", "114.23㎡", "变卖"]
      }
    ],
    show: false, //弹出框
    showdel: false
  },
  chooserRole() { //认证用户，只能选中不能取消
    let that = this;
    let checked = this.data.actived_role;
    if (checked.chek == 0) {
      let data = {
        pk: that.data.userData.id
      }
      // console.log(data)
      app.ports.api48({
        data
      }).then((res) => {
        // console.log(res)
        checked.chek = 1;
        this.setData({
          actived_role: checked
        })
      }).catch(() => {
        console.error("将用户设置为已认证失败！")
      })
    } else {
      return
    }
  },
  choose(e) { //市场专员、合伙人管理、合伙专员互斥
    var that = this;
    var index = e.currentTarget.dataset.index;
    //  console.log(index)
    var cheks = that.data.cheks;
    if (index == 4) {
      if (cheks[4].chek == 1) {
        cheks[4].chek = 0
      } else {
        cheks[4].chek = 1
      }
      cheks[6].chek = 0
      cheks[5].chek = 0
    } else if (index == 5) {
      cheks[4].chek = 0
      cheks[6].chek = 0
      if (cheks[5].chek == 1) {
        cheks[5].chek = 0
      } else {
        cheks[5].chek = 1
      }
    } else if (index == 6) {
      if (cheks[6].chek == 1) {
        cheks[6].chek = 0
      } else {
        cheks[6].chek = 1
      }
      cheks[4].chek = 0
      cheks[5].chek = 0
    } else {
      if (cheks[index].chek == 0) {
        cheks[index].chek = 1
      } else {
        cheks[index].chek = 0
      }
    }
    that.setData({
      cheks: cheks
    })
  },
  showDialog(e) {
    this.setData({
      show: true
    })
  },
  delDialog(e) {
    let that = this;
   that.data.options.results.forEach(item => {
      if(item.checked === true){
        this.setData({
          showdel: true
        })
      }
    });
   
  },
  determine(e) { //增加弹出框  点击确定触发 ，增加组别
    var that = this;
    // console.log(e)
    let title = that.data.value
    let group = {
      parent_group_pk: that.data.userMedata.group_id
    }
    if (that.data.userMedata.group_id == null) {
      wx.showToast({
        title: '当前您没有组别，无法创建组别关系！',
        icon: 'none',
        duration: 1500
      })
      return false
    }
    let data = {
      "title": title
    }
    // console.log(that.data.userData)
    // console.log(group, data) //当组别不同时，不能增加
    // if (that.data.userMedata.organization_id != that.data.userData.organization_id) {
    if (that.data.userMedata.group_id != that.data.userData.group_id) {
      wx.showToast({
        title: '该用户和你属于不同组织，无法操作',
        icon: 'none',
        duration: 1500
      })
    } else {
      app.ports.api49({
        data,
        group
      }).then((res) => {
        // console.log(res)
        wx.showToast({
          title: '增加成功',
          icon: 'none',
          duration: 1500
        })
        that.groups();
      }).catch((error) => {
        console.log(error)
      })
    }
  },
  onClose() {
    this.setData({
      show: false
    });
    this.setData({
      showdel: false
    });
  }, //关闭增加组别
  dialogSet(e) {
    this.setData({
      value: e.detail.value
    })
  }, //增加输入框
  authorization() { //获取全部选中状态，授权
    // console.log(this.data.cheks)
    let that = this;
    let checked = this.data.cheks;
    let liky = checked.filter((p) => {
      return p.chek == 1
    }) //过滤出选中的权限，即要给被点击用户的权限
    let v = [];
    for (let i in liky) {
      v[i] = liky[i]['name']
    }
    let url = {
      pk: that.data.userData.id
    }
    // console.log(data,v)
    app.ports.api45({
      url: url,
      data: {roleIds: v, id: url.pk}
    }).then((res) => {
      // console.log(res)
      wx.showToast({
        title: '授权成功',
        icon: 'none',
        duration: 1500
      })
    }).catch(() => {
      console.error("增加权限出错了！")
    })
  },
  radioChange(e) { //改变分组
    let that = this;
    let groupId = e.currentTarget.dataset.id;
    let data = {
      user_pk: that.data.userData.id,
      group_pk: groupId
    };
    if(groupId != that.data.groupId){
      that.data.modify = data;
      for(let i = 0;i<that.data.options.results.length;i++){
        that.data.options.results[i].checked = false
      }
      that.data.options.results[e.currentTarget.dataset.index].checked =true
      that.setData({
        options:that.data.options
      })
    }else{
      app.ports.removeGroup({
        data
      }).then((res) => {
        that.data.groupId = null
        wx.showToast({
          title: '移除成功',
          icon: 'none',
          duration: 1500
        })
        that.data.options.results[e.currentTarget.dataset.index].checked = false;
        that.setData({
          options:that.data.options
        })
      }).catch(() => {
        console.error("移除分组失败！")
      })
    }
  },
  modify(){
    let that = this;
    let data = that.data.modify;
    // console.log(data)
      app.ports.api50({
        data
      }).then((res) => {
        that.data.groupId = data.group_pk
        wx.showToast({
          title: '设置成功',
          icon: 'none',
          duration: 1500
        })
      }).catch(() => {
        console.error("改变分组失败！")
      })
  },
  radioChangedel(e) { //选择删除分组选项
    // console.log(e.detail.value)
    this.setData({
      delGroupId: e.detail.value
    })
  },
  delGroup() { //删除分组
    let that = this;
    let data = {
      group_pk:  that.data.modify.group_pk
    }
    app.ports.api51({
      data
    }).then((res) => {
      // console.log(res)
      wx.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 1500,
        success(res){
          if(that.data.options.results.length == 1){
            if(that.data.offset > 0){
              that.setData({
                offset:(that.data.offset-=1 * 10)
              })
            }
          }
          that.groups()
        }
      })
     
    }).catch(() => {
      console.error("删除分组错误！")
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  roleAllList() {
    let that = this;
    app.ports.api41({}).then((res) => { //获取所有权限集合
      // console.log(res)
      for (let i in that.data.cheks) {
        for (let j in res.data.results) {
          if (that.data.cheks[i].code == res.data.results[j].code) {
            that.data.cheks[i].name = res.data.results[j].id
          }
        }
      }

      // console.log("that.data.cheks ==== ", that.data.cheks)
    }).catch(() => {
      console.error('权限管理获取所有用户信息错了！')
    });
  },
  userInfo() {
    let that = this;
    let data = {

      user_pk: that.data.userData.id
    }
    app.ports.api53({
      data
    }).then((res) => {
      // console.log(res.data,'userInfo')
      // that.setData({
      //   userData:res.data
      // })
      for (let i in that.data.cheks) {
        for (let j in res.data.granted_role_set) {
          if (that.data.cheks[i].name == res.data.granted_role_set[j].id) { 
            that.data.cheks[i].chek = 1
          }
        }
      } //匹配当前被操作者所拥有的权限
      that.setData({
        cheks: that.data.cheks
      })
    }).catch(() => {
      console.error("拉取被操作者失败！")
    })
  },
  onLoad: function (options) {
    // this.organ()
    var that = this;
    that.roleAllList();
    let dataList = JSON.parse(decodeURIComponent(options.id));
    // console.log(dataList, "======11122======")
    this.setData({
      userData: dataList,
      identity: wx.getStorageSync('identity')
    }) //获取被点击用户的数据
    // console.log(dataList)
    if (dataList.is_verified) { //获取是否认证
      that.data.actived_role.chek = 1
      that.setData({
        actived_role: that.data.actived_role
      })
    }
    // that.data.cheks.filter((p)=>{ //匹配自身权限，使其单选亮起
    //   if(p.name == dataList.active_role_id){  p.chek = 1; }
    // })
    that.setData({
      cheks: that.data.cheks
    }); //实时更改
    app.ports.api30({}).then((res) => { //拉取操作者自身信息
      that.setData({
        userMedata: res.data
      })
      // console.log(res.data)

      // let liky = res.data.granted_role_set.filter((p) => {
      //   return p.id == res.data.active_role_id
      // })

      // that.setData({ roleIndex : liky[0].code })
      // let code = liky[0].code;
      let code = res.data.role_code;
      var roleShow;
      var showindex = true;
      //超级管理员、平台管理员、商户管理员、代理公司管理员
      switch (code) {
        case 'platform_admin':
        case 'super_admin':
        case 'agence_admin':
        case 'renter_admin':
          roleShow = 0
          break;
        case 'renter_ceo':
          roleShow = 1
          break;
        case 'renter_marketing_manager':
          roleShow = 2
          break;
        case 'renter_finance_manager':
        case 'renter_logistics_manager':
          roleShow = 2
          showindex = false
          break;
        case 'renter_outsourcing_manager':
          roleShow = 3
          break;
          case 'renter_outsourcing_staff':
            roleShow = 4
            break;
        default:
          roleShow = 5
          break;
      }
      that.setData({
        roleShow:roleShow,
        showindex:showindex
      })
    }).catch(() => {
      console.error('权限管理页面拉取自身信息出错！')
    });
    that.userInfo(); //拉取被操作者的权限
    that.groups(); // 获取分组
  
    that.history()
  },
  groups() { //获取分组      
    let that = this;
    var data = {
      // limit:10,
      // offset:that.data.offset
      page_size: 10,
      page_token: that.data.offset
    }
    app.ports.api46({data}).then((res) => {
      let data = res.data;
      data.results.filter((p) => {
        if (p.id == that.data.userData.group_id) {
          // console.log(that.data.userData.group_id, "===============1112111213333")
          that.data.groupId = p.id
          p.checked = true;
         
        }else{
          p.checked = false;
        }
      })
      that.setData({
        options: data
      })
    }).catch(() => {
      console.error("获取所有的组别错误！")
    })
  },
  history() {//浏览记录
    var that = this;
    var listId = [];
    var houses = [];
    app.ports.userHistory({
      id: that.data.userData.id
    }).then(res => {
      res.data.results.forEach(item => {
        var status = item.houseCategory == 1 ? 0 : 1;
        item.url = '../details/details?id=' + item.houseId + '&status='+status
      })
      that.setData({
        list: res.data
      })

      // console.log(res.data)
      // for (var i = 0; i < res.data.houses.buckets.length; i++) {
      //   // console.log(res.data.houses.buckets[i].latest_access_logs.hits.hits[0]._source)
      //   listId.push(res.data.houses.buckets[i].latest_access_logs.hits.hits[0]._source.house_id)
      //   houses.push(res.data.houses.buckets[i].latest_access_logs.hits.hits[0])
      // }

      // app.ports.gethouses({
      //   data: listId
      // }).then(obj => {
      //   var obj = obj.data;
      //   for (let i = 0; i < obj.results.length; i++) {
      //     obj.results[i].house_category = '折扣'
      //     for (var j = 0; j < houses.length; j++) {
      //       if (obj.results[i].id == res.data.houses.buckets[j].latest_access_logs.hits.hits[0]._source.house_id) {
      //         obj.results[i].browseDate = app.timeFormat(res.data.houses.buckets[j].latest_access_logs.hits.hits[0]._source.access_time, true)
      //         obj.results[i].browseTime = res.data.houses.buckets[j].latest_access_logs.hits.hits[0]._source.access_interval_seconds
            
      //         // obj.results[i].type = res.data.houses.buckets[j].latest_access_logs.hits.hits[0]._source.house_category
      //       }
      //     }
      //     if (obj.results[i].type == 1) {
      //       obj.results[i].house_category = '优选'
      //       obj.results[i].tags = [{
      //         name: obj.results[i].built_up_area_square_centimeter + '㎡'
      //       }, {
      //         name: obj.results[i].discount_rate + '折'
      //       }, {
      //         name: obj.results[i].stage
      //       }]
      //       obj.results[i].market_price_yuan = Math.floor((obj.results[i].market_price_yuan / 10000));
      //       obj.results[i].price_yuan = Math.floor((obj.results[i].price_yuan / 10000));
      //       obj.results[i].time = app.timeFormat(obj.results[i].start_time) + '-' + app.timeFormat(obj.results[i].end_time)
      //     } else {
      //       obj.results[i].time = app.timeFormat(obj.results[i].upload_time)
      //     }
      //     obj.results[i].url = '../details/details?id=' + obj.results[i].id
      //   }
      //   that.setData({
      //     list: obj
      //   })
      // }).catch(() => {
      //   console.error('浏览记录列表')
      // })
    }).catch(() => {
      console.error('浏览记录列表')
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 
  historyShow() {
    this.setData({
      historyShow: true
    })
  },
  onClickHide() {
    this.setData({
      historyShow: false
    })
  },
  navTo: function (e) { //跳转
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  },
  next(){//组别下一页
    var that = this;
    if(that.data.options.results.length == 10){
      that.setData({
        offset:(that.data.offset+=1)
      })
      that.groups()
    }
   
  },
  previous(){//组别上一页
    var that = this;
    // console.log('上一页')
    if(that.data.offset > 0){
      that.setData({
        offset:(that.data.offset-=1)
      })
      that.groups()
    }
  }
})